@include "misc.awk"
@include "reader.awk"
@include "euclid.awk"

function sample(     _locals) {
    FS=","
    args("seed=1;samples=256;in=/dev/stdin;handler=rowPrint",Opt,_locals) 
    seed(Opt["seed"]) 
    sampler(Opt["in"],Opt["samples"])
}
function anyRow(t)           { return anyi(t["rows"]) + 1 }
function sampler(f,n,   t)   { lines(f,t); sampler1(t,n,n) }
function sampler1(t,n,tries) { while (n--)  closest(t, anyRow(t), tries) }

function closest(t,r1,tries,       min,tmp,d,mine,r2) {
    min = 1000000000000
    r2  = r1
    while(tries--) {
        tmp = anyRow(t)
        if (tmp==r1) continue 
        d = dist(t,r1,tmp)
        if (d  < min) {
            min = d
            r2  = tmp }}
    return inBetween(t,r1,r2)
}
function inBetween(t,r1,r2,   row,action,sep,c) {
    for(c=t["cols"]; c>=1; c--)
        row[c] = c in t["use"] ? inBetween1(t,c,r1,r2) : "?"
    action = Opt["handler"]
    @action(row)
}
function inBetween1(t,c,r1,r2,      out,v1,v2) {
    v1 = t[r1][c]
    v2 = t[r2][c]
    if      (v1 == "?")    out= v2
    else if (v2 == "?")    out= v1
    else if (t["num"][c])  out = within(v1,v2)
    else out = rand() > 0.5 ? v1 : v2;
    return out
}
